package com.project.lk.nurseapp.common.socket;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.common.websocket.IMsgInfo;
import com.project.lk.nurseapp.common.websocket.MsgBean;
import com.project.lk.nurseapp.utils.JsonUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Set;

/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class NIOSClient {
	/* 发送数据缓冲区 */
	private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);

	/* 接受数据缓冲区 */
	private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);

	/* 服务器端地址 */
	private InetSocketAddress SERVER;

	private static Selector selector;

	private static SocketChannel client;

	private static String receiveText;

	private static String sendText;

	private static int count = 0;
	private  static NIOSClient niosClient;

	public static NIOSClient getNIOSClient(String hostname,String  port){
		synchronized (NIOSClient.class){
			if (niosClient!=null){
				return niosClient;
			}else {

				return new NIOSClient(hostname,Integer.parseInt(port));
			}

		}

	}
	public NIOSClient(String hostname,int port) {
		SERVER = new InetSocketAddress(hostname, port);
		new Thread(){
			@Override
			public void run() {
				if (isConnected()) {
					init();
				}
			}
		};
		init();
	}
	/**
	 * 检查当前是否连接
	 *
	 * @param
	 * @return true表示当前网络处于连接状态，否则返回false
	 */
	public static boolean isConnected() {
		ConnectivityManager cm = (ConnectivityManager) BaseApp.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			return true;
		}
		return false;
	}
	public void init() {
		try {
			/*
			 * 客户端向服务器端发起建立连接请求
			 */
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			selector = Selector.open();
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
			socketChannel.connect(SERVER);
			/*
			 * 轮询监听客户端上注册事件的发生
			 */

				while (isConn) {  // 默认true
					selector.select();
					Set<SelectionKey> keySet = selector.selectedKeys();
					for (final SelectionKey key : keySet) {
						handle(key);
					}
					keySet.clear();

					}
			if (!isConn){
				throw new Exception();
			}

		} catch (Exception e) {
			e.printStackTrace();

			Log.e("MLOG","SOCKET1>>>>>");
		}
	}

	public boolean sendMsg(){
		if (client!=null) {
			if (client.isConnectionPending()) {
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}


	}

	public void sendWork() throws IOException{


		while (true) {
				sBuffer.clear();
			/*
			* 未注册WRITE事件，因为大部分时间channel都是可以写的
			*/
			if (new UserInfoUtils().getAccountId()!=null) {
				sBuffer.put(("{\"accountId\":" +"\""+new UserInfoUtils().getAccountId()+"\"}").getBytes());
				sBuffer.flip();
				client.write(sBuffer);
			}else {
			}

			SystemClock.sleep(6000);
		}
	}

	public  boolean isConn=true;
	private void handle(final SelectionKey selectionKey) throws Exception {
		if (selectionKey.isConnectable()) {
			/*
			 * 连接建立事件，已成功连接至服务器
			 */
			client = (SocketChannel) selectionKey.channel();
			if (client.isConnectionPending()) {
				client.finishConnect();
				Log.e("MLOG","connect success !");
//				sBuffer.clear();
//				sBuffer.put(("{\"userid\":"+new UserInfoUtils().getUserid()+",\"time\":\"" + new Date().getTime() + "\"}").getBytes());
//				sBuffer.flip();
//				client.write(sBuffer);// 发送信息至服务器
				/*
				 * 原文来自站长网 启动线程一直监听客户端输入，有信息输入则发往服务器端 因为输入流是阻塞的，所以单独线程监听
				 */
			new Thread() {
			@Override
			public void run() {
				try {
					sendWork();//发消息给服务端
				} catch (IOException e) {
					e.printStackTrace();
					isConn=false;
//					client.c
//					mInfo.postException();
//					Log.e("MLOG","SOCKET》》》》》》》》》》》》》》》");
//					EventBus.getDefault().post();
				}
			};
		}.start();

			}
			// 注册读事件
			client.register(selector, SelectionKey.OP_READ);
		} else if (selectionKey.isReadable()) {
			/*
			 * 读事件触发 有从服务器端发送过来的信息，读取输出到屏幕上后，继续注册读事件 监听服务器端发送信息
			 */

					try {
					client = (SocketChannel) selectionKey.channel();
					rBuffer.clear();

						count = client.read(rBuffer);

					if (count > 0) {
						receiveText = new String(rBuffer.array(), 0, count);
						MsgBean bean = (MsgBean) JsonUtils.getJsonUtils()
								.toObject(new TypeToken<MsgBean>(){}.getType(),receiveText);
						Log.e("MLOG",receiveText);
						EventBus.getDefault().post(new IMsgInfo(bean));
						// showNoticeMore(mContext,info,info, PlayGameActivity.class,machineid+"",machineno, Integer.parseInt(typeId));
						client = (SocketChannel) selectionKey.channel();
						client.register(selector, SelectionKey.OP_READ);

					}
					} catch (IOException e) {
							e.printStackTrace();
					}
		}
	}


	public interface IPostExceptionInfo{
		void postException();
	}
	IPostExceptionInfo mInfo;

	public void setIPostExcetion(IPostExceptionInfo info){
		this.mInfo=info;
	}



}
